package artid.com.arttogoa.app;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.xutils.x;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Notification;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.StrictMode;
import android.provider.Settings.Secure;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import artid.com.arttogoa.ChatActivity;
import artid.com.arttogoa.MainActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.SendHxMessage_Utils;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.util.VeDate;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.controller.EaseUI.EaseSettingsProvider;
import com.hyphenate.easeui.model.EaseNotifier;
import com.hyphenate.easeui.model.EaseNotifier.EaseNotificationInfoProvider;
import com.hyphenate.util.EMLog;
import com.iflytek.cloud.SpeechUtility;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

public class ArtWorkApp extends MultiDexApplication {
    /**
     * Activity列表
     */
    public static List<Activity> activityList = new LinkedList<Activity>();
    /**
     * 备案过程列表
     */
    private List<Activity> artActivityList = new LinkedList<Activity>();

    private static String androidId;
    /**
     * 全局唯一实例
     */
    private static ArtWorkApp instance;
    /**
     * 上下文对象
     */
    private static Context mContext = null;
    public static final boolean DEVELOPER_MODE = false;
    @SuppressWarnings("unused")

    private static ArtWorkApp app;

    /**
     * 环信
     */
    private EMConnectionListener connectionListener;
    /**
     * 当前打开的Activity
     */
    public static Activity currentActivity;

    /**
     * 获取类实例对象b
     *
     * @return MyActivityManager
     */
    public static ArtWorkApp getInstance() {
        if (null == instance) {
            instance = new ArtWorkApp();
        }
        return instance;
    }

    /**
     * 吧 保存Activity到现有列表中
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public void RemoveActivity(Activity activity) {
        activityList.remove(activity);
    }

    public void RemoveActivity(String activityName) {
        for (int i = 0; i < activityList.size(); i++) {
            if (activityName.equals(activityList.get(i).getClass().getSimpleName().toString())) {
                activityList.remove(i);
            }
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 把备案保存备案Activity到现有列表中
     *
     * @param activity
     */
    public void addArtActivity(Activity activity) {
        artActivityList.add(activity);
    }

    /**
     * 关闭保存的Activity
     */
    public void exit() {
        Log.d("log", "要关闭的Activity：" + activityList.toString());
        if (activityList != null) {
            Activity activity;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }

                    activity = null;
                }
                activityList.remove(i);
                i--;
            }
        }
    }

    /**
     * 关闭保存的Activity
     */
    public void exit(int position) {
        if (activityList != null && activityList.size() >= position) {
            activityList.get(position).finish();
        }
    }

    /**
     * 关闭保存的备案Activity
     */
    public void artExit() {
        if (artActivityList != null) {
            Activity activity;
            for (int i = 0; i < artActivityList.size(); i++) {
                activity = artActivityList.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }

                    activity = null;
                }
                artActivityList.remove(i);
                i--;
            }
        }
    }

    @SuppressWarnings("unused")
    @Override
    public void onCreate() {
        //Xutils初始化
        x.Ext.init(this);
        // 是否输出debug日志
        x.Ext.setDebug(false);
        if (DEVELOPER_MODE
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll().penaltyDialog().build());

            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectAll().penaltyDeath().build());
        }
        String s;
        super.onCreate();
        //注册讯飞语音
        SpeechUtility.createUtility(ArtWorkApp.this, "appid=" + getString(R.string.app_id));
        mContext = getApplicationContext();
        app = this;
        getAndroidId();
        initImageLoader(getApplicationContext());

        //环信注册
        MultiDex.install(this);
        mContext = getApplicationContext();
        instance = this;
        EMOptions options = new EMOptions();
        options.setAutoLogin(false);
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        //环信小米推送服务注册
        options.setMipushConfig(mContext.getResources().getString(R.string.mipushAppid), mContext.getResources().getString(R.string.mipushAppkey));
        if (EaseUI.getInstance().init(mContext, options)) {
            EMClient.getInstance().addConnectionListener(connectionListener);
            easeUI = EaseUI.getInstance();
            broadcastManager = LocalBroadcastManager.getInstance(mContext);
            //调用easeui的api设置providers
            setEaseUIProviders();
            //注册消息事件监听
            registerEventListener();
            //设置消息是否通知
            setEaseUIIsOpenNotification();
            EMClient.getInstance().chatManager().addMessageListener(msgListener);
        }
        // 友盟注册
        //注册推送服务，每次调用register方法都会回调该接口
        PushAgent.getInstance(this).register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.d("log", "友盟ID：" + deviceToken);
                PushAgent.getInstance(mContext).setMessageHandler(mUmengMessageHandler);
                PushAgent.getInstance(mContext).setNotificationClickHandler(notificationClickHandler);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.d("log", "初始化友盟错误：" + s.toString() + "===" + s1.toString());
            }
        });
    }


    public static Context getContext() {
        return mContext;
    }

    public static String getAndroidId() {
        if (TextUtils.isEmpty(androidId)) {
            androidId = Secure.getString(mContext.getContentResolver(),
                    Secure.ANDROID_ID);
        }
        return androidId;
    }

    public static void initImageLoader(Context context) {
        //		ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);//默认配置(开启这个下面的就可以不用设置)
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.yspba_img_mor) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.yspba_img_mor) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.yspba_img_mor) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(false)  // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(0)  // 下载前的延迟时间
                .cacheInMemory(false) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中
                .considerExifParams(false) // default
                .imageScaleType(ImageScaleType.EXACTLY) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
                //		.displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)
                .build();
        File cacheDir = StorageUtils.getOwnCacheDirectory(context, "imageloader/yjb/Cache"); //缓存文件夹路径
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .memoryCacheExtraOptions(1024, 800) // default = device screen dimensions 内存缓存文件的最大长宽
                .diskCacheExtraOptions(1024, 1024, null)  // 本地缓存的详细信息(缓存的最大长宽)，最好不要设置这个
                .threadPoolSize(1) // default  线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(1 * 1024 * 1080)) //可以通过自己的内存缓存实现
                .memoryCacheSize(1 * 1024 * 1080)  // 内存缓存的最大值
                .memoryCacheSizePercentage(1) // default
                .diskCacheSize(100 * 1024 * 1080) // 50 Mb sd卡(本地)缓存的最大值
                .diskCacheFileCount(100)  // 可以缓存的文件数量
                // default为使用HASHCODE对UIL进行加密命名， 还可以用MD5(new Md5FileNameGenerator())加密
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .imageDownloader(new BaseImageDownloader(context)) // default
                .imageDecoder(new BaseImageDecoder(true)) // default
                .diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
//		.writeDebugLogs() // 打印debug log
                .defaultDisplayImageOptions(options)
                .build(); //开始构建
        ImageLoader.getInstance().init(config);
    }

    /**
     * 清除ImageLoader缓存
     *
     * @param view
     */
    public static void ClearImageLoaderMemoryClick() {
        ImageLoader.getInstance().clearMemoryCache();  // 清除内存缓存
    }

    public void onClearDiskClick() {
        ImageLoader.getInstance().clearDiskCache();  // 清除本地缓存
    }

    /**
     * 获取友盟推送信息
     */
    UmengMessageHandler mUmengMessageHandler = new UmengMessageHandler() {
        @Override
            public Notification getNotification(Context arg0, UMessage mUMessage) {
                Notification mNotification = null;
                if (setPushSetting(1)) {
                    PushAgent.getInstance(mContext).setNotificaitonOnForeground(true);
                    if (setPushSetting(4)) {
                        PushAgent.getInstance(mContext).setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);//振动开启
                    } else {
                        PushAgent.getInstance(mContext).setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);//振动关闭
                    }
                    if (setPushSetting(3)) {
                        PushAgent.getInstance(mContext).setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);//声音开启
                    } else {
                        PushAgent.getInstance(mContext).setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);//声音关闭
                    }
                } else {
                    PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                }
                if (mUMessage.extra != null) {
                    if ("1".equals(mUMessage.extra.get("messtype"))) {
                        MySharedPreferences.getMySharedPreferences(mContext).setValue("isReplyPush" + AppUtil.getUser().getUid(), "true");
                    }
                    Intent intent0 = new Intent("com.Push.receiver");
                    intent0.putExtra("PushType", mUMessage.extra.get("messtype"));
                    mContext.sendBroadcast(intent0);
                    //发送到主页用来即使更改未读消息状态显示
                    Intent intent2 = new Intent("com.MainActivity.receiver");
                    intent2.putExtra("PushType", mUMessage.extra.get("messtype"));
                    intent2.putExtra("UmengPush", true);
                    mContext.sendBroadcast(intent2);

                    Intent intent3 = new Intent("com.PersonalActivity.receiver");
                    intent3.putExtra("PushType", mUMessage.extra.get("messtype"));
                    intent3.putExtra("UmengPush", true);
                    mContext.sendBroadcast(intent3);

                    Intent intent4 = new Intent("com.MessageActivity.receiver");
                    intent4.putExtra("UmengPush", true);
                    intent4.putExtra("PushType", mUMessage.extra.get("messtype"));
                    mContext.sendBroadcast(intent4);

                    if (isAppOnForeground(mContext)) {
                        //判断App是否启动，启动的情况下不显示通知栏
                        if ("0".equals(mUMessage.extra.get("messtype"))) {
                            //设置通知栏不显示
                            PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                            ToastUtil.toast(mContext, "您有一个新的系统消息，请去查看！");
                        } else if ("1".equals(mUMessage.extra.get("messtype"))) {
                            //设置通知栏不显示
                            PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                            ToastUtil.toast(mContext, "您有一个新的回复消息，请去查看！");
                        } else if ("2".equals(mUMessage.extra.get("messtype"))) {
                            //设置通知栏不显示
                            PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                            ToastUtil.toast(mContext, "您有一个新的付款消息，请去查看！");
                        } else if ("4".equals(mUMessage.extra.get("messtype"))) {
                            //设置通知栏不显示
                            PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                            ToastUtil.toast(mContext, "您有一个新的收货消息，请去查看！");
                        } else if ("9".equals(mUMessage.extra.get("messtype"))) {
                            //设置通知栏不显示
                            PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                            ToastUtil.toast(mContext, "您有一个新的审核消息，请去查看！");
                        }
                    } else {
                        PushAgent.getInstance(mContext).setNotificaitonOnForeground(true);
                    }
                }
                return mNotification;
            }

            ;

            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                Log.d("log", "推送消息2：" + msg.text);
            }
    };

    /**
     * 友盟通知栏点击事件
     */
    UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
        @Override
        public void dealWithCustomAction(Context context, UMessage msg) {
            Log.d("log", "友盟通知栏：" + msg.extra.toString());
            MainActivity.PushMessage = msg.extra;
            //判断系统消息 1为评论回复消息，0为系统消息
            String messtype = msg.extra.get("messtype");
            String art_id = msg.extra.get("art_id");
            //判断App是否已经启动
            if ("0".equals(messtype) || "1".equals(messtype) || "2".equals(messtype) || "4".equals(messtype) || "9".equals(messtype)) {
                //如果是回复和系统消息直接启动APP（App启动的情况下系统/回复/收款/已签收/消息通知栏不会显示）
                startAPP(mContext, "artid.com.arttogoa");
            }
        }
    };


    private LocalBroadcastManager broadcastManager;

    protected void setGlobalListeners() {
        //注册连接监听
        EMClient.getInstance().addConnectionListener(connectionListener);
        //注册消息事件监听
        registerEventListener();

    }

    void initEasyTalk() {

    }

    public EaseNotifier getNotifier() {
        return easeUI.getNotifier();
    }

    public static EaseUI easeUI;
    protected EMMessageListener messageListener = null;

    protected void registerEventListener() {
        messageListener = new EMMessageListener() {
            private BroadcastReceiver broadCastReceiver = null;

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d("环信消息", "onMessageReceived id : " + message.getMsgId());
                    //应用在后台，不需要刷新UI,通知栏提示新消息
                    if (!easeUI.hasForegroundActivies()) {
                        getNotifier().onNewMsg(message);
                    }
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d("环信消息", "收到透传消息");
                    //获取消息body
                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                    final String action = cmdMsgBody.action();//获取自定义action
                    ToastUtil.toast(mContext, "接收到信息：" + messages.toString());
                    Log.d("log", "接收到信息：" + messages.toString());
                    //获取扩展属性 此处省略
                    //message.getStringAttribute("");
                    EMLog.d("环信消息", String.format("透传消息：action:%s,message:%s", action, message.toString()));
                    final String str = mContext.getString(R.string.receive_the_passthrough);

                    final String CMD_TOAST_BROADCAST = "hyphenate.demo.cmd.toast";
                    IntentFilter cmdFilter = new IntentFilter(CMD_TOAST_BROADCAST);

                    if (broadCastReceiver == null) {
                        broadCastReceiver = new BroadcastReceiver() {
                            @Override
                            public void onReceive(Context context, Intent intent) {
                                // TODO Auto-generated method stub
                                Toast.makeText(mContext, intent.getStringExtra("cmd_value"), Toast.LENGTH_SHORT).show();
                            }
                        };

                        //注册广播接收者
                        mContext.registerReceiver(broadCastReceiver, cmdFilter);
                    }

                    Intent broadcastIntent = new Intent(CMD_TOAST_BROADCAST);
                    broadcastIntent.putExtra("cmd_value", str + action);
                    mContext.sendBroadcast(broadcastIntent, null);
                }
            }


            @Override
            public void onMessageRead(List<EMMessage> list) {
                // 已读回执
            }

            @Override
            public void onMessageDelivered(List<EMMessage> list) {
                // 已送达
            }

            @Override
            public void onMessageChanged(EMMessage arg0, Object arg1) {
                // TODO Auto-generated method stub
                // 消息状态变动
            }

        };

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    /**
     * 设置是否开启环信通知
     */
    public static void setEaseUIIsOpenNotification() {
        easeUI.setSettingsProvider(new EaseSettingsProvider() {

            @Override
            public boolean isSpeakerOpened() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean isMsgVibrateAllowed(EMMessage message) {
                // TODO Auto-generated method stub
                //设置是否开启震动
                Log.d("log", "环信震动：" + setPushSetting(4));
                return setPushSetting(4);
            }

            @Override
            public boolean isMsgSoundAllowed(EMMessage message) {
                // TODO Auto-generated method stub
                //设置是否开启响铃
                Log.d("log", "环信铃声：" + setPushSetting(3));
                return setPushSetting(3);
            }

            @Override
            public boolean isMsgNotifyAllowed(EMMessage message) {
                // TODO Auto-generated method stub
                //设置是否开启通知栏
                return setPushSetting(1);
            }
        });
    }

    /**
     * 环信通知栏
     */
    protected void setEaseUIProviders() {
        //不设置，则使用easeui默认的
        easeUI.getNotifier().setNotificationInfoProvider(new EaseNotificationInfoProvider() {

            @Override
            public String getTitle(EMMessage message) {
                //修改标题,这里使用默认
                return null;
            }

            @Override
            public int getSmallIcon(EMMessage message) {
                //设置小图标，这里为默认
                return 0;
            }

            @Override
            public String getDisplayedText(EMMessage message) {
                // 设置状态栏的消息提示，可以根据message的类型做相应提示
                return null;
            }

            @Override
            public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {
                return null;
                // return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
            }

            @Override
            public Intent getLaunchIntent(EMMessage message) {
                //设置点击通知栏跳转事件
                if (MainActivity.isLogin == true) {
                    if (!isForeground(mContext, "artid.com.arttogoa.ChatActivity")) {
                        return SendHxMessage_Utils.goChatCallBackIntent(mContext, message);
                    }
                } else {
                    MainActivity.friendAvatar = message.getStringAttribute("artistURL", "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
                    SendHxMessage_Utils.mEMMessage = message;
                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.putExtra("isHxNotification", true);
                    return intent;
                }
                return null;
            }
        });
    }

    /**
     * 环信消息接收
     */
    EMMessageListener msgListener = new EMMessageListener() {


        @Override
        public void onMessageRead(List<EMMessage> list) {
            // 已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {
            // 已送达
        }

        @Override
        public void onMessageChanged(EMMessage arg0, Object arg1) {
            // TODO Auto-generated method stub
            // 消息状态变动
        }


        @Override
        public void onCmdMessageReceived(List<EMMessage> list_EMMessage) {
            // TODO Auto-generated method stub
            // 透传消息
            Log.d("log", "环信透传消息:" + list_EMMessage.toString());

        }

        @Override
        public void onMessageReceived(final List<EMMessage> list_EMMessage) {
            // TODO Auto-generated method stub

            //发送到主页用来即使更改未读消息状态显示
            Intent intent = new Intent("com.MainActivity.receiver");
            intent.putExtra("HXPush", true);
            mContext.sendBroadcast(intent);

            Intent intent2 = new Intent("com.PersonalActivity.receiver");
            intent2.putExtra("HXPush", true);
            mContext.sendBroadcast(intent2);

            Intent intent3 = new Intent("com.MessageActivity.receiver");
            intent3.putExtra("HXPush", true);
            mContext.sendBroadcast(intent3);
        }
    };

    /**
     * 收到环信消息提示框
     *
     * @param list
     */
    public static void showMessageDialog(final EMMessage message) {
        if (isAppOnForeground(mContext) == false) {
            return;
        }
        try {
            if (AlertUtils.alertDialog != null) {
                AlertUtils.alertDialog.dismiss();
                AlertUtils.alertDialog = null;
            }
            if (isForeground(mContext, StringUtils.substringBeforeLast(currentActivity.toString(), "@")) == true) {
                //判断当天Activity是否存在如果存在显示Dialog，反之土司
                if (isForeground(mContext, "artid.com.arttogoa.ChatActivity") == false && isAppOnForeground(mContext)) {
                    AlertUtils.MessageAlertDialog(currentActivity, "您有新的询价信息是否进入聊天?", Integer.parseInt(NetUtils
                            .getDisplayMetrics(currentActivity).get(NetUtils.DM_WIDTH)), new OnClickListener() {
                        private View s;

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            switch (v.getId()) {
                                case R.id.tv_ok:
                                    //确定
                                    // 进入聊天页面
                                    Intent intent = new Intent(mContext, ChatActivity.class);
                                    try {
                                        MainActivity.friendAvatar = message.getStringAttribute("artistURL", "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
                                        SendHxMessage_Utils.mEMMessage = message;
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    mContext.startActivity(intent);
                                    AlertUtils.dismiss();
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
                }
            } else {
                ToastUtil.toast(mContext, "您有一个新的询价消息，请去查看！");
            }
        } catch (Exception e) {
            // TODO: handle exception
            Log.d("log", "环信消息提示框出错：" + currentActivity.getPackageName());
        }
    }

    /**
     * 设置推送是否响铃、震动、通知栏是否显示
     */
    public static Boolean setPushSetting(int type) {
        int NewMessageNotification = 1;//通知栏
        int NoDisturbing = 2;//免打扰
        int Sound = 3;//铃声
        int Vibration = 4;//震动
        if (NewMessageNotification == type) {
            if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("NewMessageNotification" + AppUtil.getUser().getUid(), "true"))) {
                return true;
            } else {
                return false;
            }
        }
        if (Sound == type) {
            if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("NewMessageNotification" + AppUtil.getUser().getUid(), "true"))) {
                if ("false".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("NoDisturbing" + AppUtil.getUser().getUid(), "false"))) {
                    if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("Sound" + AppUtil.getUser().getUid(), "true"))) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    if (VeDate.timeBucket(6, 22)) {
                        if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("Sound" + AppUtil.getUser().getUid(), "true"))) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        if (Vibration == type) {
            if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("NewMessageNotification" + AppUtil.getUser().getUid(), "true"))) {
                if ("false".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("NoDisturbing" + AppUtil.getUser().getUid(), "false"))) {
                    if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("Vibration" + AppUtil.getUser().getUid(), "true"))) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    if (VeDate.timeBucket(6, 22)) {
                        if ("true".equals(MySharedPreferences.getMySharedPreferences(mContext).getValue("Vibration" + AppUtil.getUser().getUid(), "true"))) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称 (例如com.text.mainActivity)
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前运行的Activity的名字
     *
     * @return
     */
    public static String getRunningActivityName(Context mContext) {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null) {
            return (runningTaskInfos.get(0).topActivity).toString();
        } else {
            return "";
        }
    }

    //在进程中去寻找当前APP的信息，判断是否在前台运行
    public static boolean isAppOnForeground(Context mContext) {
        ActivityManager activityManager = (ActivityManager) mContext.getApplicationContext().getSystemService(
                Context.ACTIVITY_SERVICE);
        String packageName = mContext.getApplicationContext().getPackageName();
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /*
     * 启动一个app
     */
    public static void startAPP(Context mContext, String appPackageName) {
        try {
            Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(appPackageName);
            mContext.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.toast(mContext, "该程序没有安装");
        }
    }

    //判断App是否运行
    private boolean APPIsRun(String MY_PKG_NAME) {

        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
                isAppRunning = true;
                Log.d("log", info.topActivity.getPackageName() + " info.baseActivity.getPackageName()=" + info.baseActivity.getPackageName());
                break;
            }
        }
        return isAppRunning;
    }

}
